﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Kalficom.Forms
{
    public partial class frmClient_Taken : Form
    {
        public frmClient_Taken()
        {
            InitializeComponent();
            conf.Icon(this);
        }

        Libraies.db db = new Libraies.db();
        Query.qry_contract query = new Query.qry_contract();
        Libraies.msg msg = new Libraies.msg();
        internal int cont_id = 0;
        internal int client_id_copy = 0;
        internal string TX_CODE = string.Empty;

        private void frmClient_Taken_Load(object sender, EventArgs e)
        {
            // Get client and zone information into comboBox
            db.FillDataSet(query.get_zone, tblZone);
            db.FillDataSet(query.get_client, tblClient);

            // Draw client and zone comboBox display two column
            drawComboBox(cboZone, "zone_code", "zone_label");
            drawComboBox(cboClientCode, "TX_CODE", "TX_NOM");

            if (TX_CODE != string.Empty) cboClientCode.SelectedValue = TX_CODE;

            // Get client taken for modify
            if (this.Tag != null)
            {
                db.FillDataSet(string.Format(query.get_clientTaken, this.Tag), tblClientTaken);
                db.FillDataSet(string.Format(query.get_taken_list, this.Tag, client_id_copy > 0 ? ",[client_taken_id] AS copy_id" : "", ""), tblTaken); //client_id_copy > 0 ? ",[client_taken_id] AS copy_id":""

                if (client_id_copy > 0)
                {
                    cboClientCode.Text = "";
                    txtClientAdr1.Text = "";
                    txtClientAdr2.Text = "";
                    txtClientAdr3.Text = "";
                    txtClientCity.Text = "";
                    txtClientMobile.Text = "";
                    txtClientName.Text = "";
                    txtClientPhone.Text = "";
                    txtClientPostal.Text = "";
              
                    this.Tag = null;
                    checkCopyRow();
                }
                else
                {
                    
                    btnCreate.Visible = true;
                }
            }

            // Set Combobox Style
            (new Libraies.ctl()).ComboBox_Style(new ComboBox[] { cboClientCode, cboZone });

            this.WindowState = FormWindowState.Maximized;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void drawComboBox(ComboBox cbo, string valueField, string displayField)
        {
            // Enable the owner draw on the ComboBox.
            cbo.DrawMode = DrawMode.OwnerDrawFixed;
            // Handle the DrawItem event to draw the items.
            cbo.DrawItem += delegate(object cmb, DrawItemEventArgs args)
            {
                // Draw the default background
                args.DrawBackground();

                // The ComboBox is bound to a DataTable,
                // so the items are DataRowView objects.
                DataRowView drv = (DataRowView)cbo.Items[args.Index];

                // Retrieve the value of each column.
                string id = drv[valueField].ToString();
                string name = drv[displayField].ToString();

                // Get the bounds for the first column
                Rectangle r1 = args.Bounds;
                r1.Width /= 3;

                // Draw the text on the first column
                using (SolidBrush sb = new SolidBrush(args.ForeColor))
                {
                    args.Graphics.DrawString(id, args.Font, sb, r1);
                }

                // Draw a line to isolate the columns 
                using (Pen p = new Pen(Color.Black))
                {
                    args.Graphics.DrawLine(p, r1.Right, 0, r1.Right, r1.Bottom);
                }

                // Get the bounds for the second column
                Rectangle r2 = args.Bounds;
                r2.X = (args.Bounds.Width / 3) + 2;
                r2.Width /= 2;

                // Draw the text on the second column
                using (SolidBrush sb = new SolidBrush(args.ForeColor))
                {
                    args.Graphics.DrawString(name, args.Font, sb, r2);
                }
            };
        }

        private void btnValidate_Click(object sender, EventArgs e)
        {
            // Check requirement field
            if (cboZone.Text.Trim() == "")
            {
                MessageBox.Show(msg.zone_codeBlankMsg, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                cboZone.Focus();
                return;
            }

            if (cboClientCode.Text.Trim() == "")
            {
                MessageBox.Show(msg.cont_clientBlankMsg, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                cboClientCode.Focus();
                return;
            }

            if (!(new Libraies.ctl()).check_ComboValue(new ComboBox[] { cboClientCode, cboZone })) return;

            DataRow row = tblClientTaken.NewRow();
            row["zone_id"] = cboZone.SelectedValue;
            row["client_taken_code"] = cboClientCode.SelectedValue;
            row["cont_id"] = cont_id;
            row["user_create"] = conf.CurUser;
            row["date_create"] = db.GetDate();

            // If form's Tag is null -> create new zone.
            // If from's Tag not null -> modify zone. (Tag is zone_id for modify)
            if (this.Tag == null)
            {

                // Check Identifiation dublicate field.
                if (db.ExecuteScalar(string.Format(query.scalarID_clientTaken, db.SqlString(cboClientCode.SelectedValue), cboZone.SelectedValue, cont_id)) != "")
                {
                    MessageBox.Show(msg.cont_codeExistMsg, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    cboZone.Focus();
                    return;
                }

                if (MessageBox.Show(msg.saveMsg, msg.captionMsg, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    // Add client taken into database.
                    if (client_id_copy == 0)
                        tblClientTaken.Rows.Add(row);
                    else
                    {
                        client_id_copy = 0;
                        tblClientTaken.Rows[0].ItemArray = row.ItemArray;
                        tblClientTaken.AcceptChanges();
                        tblClientTaken.Rows[0].SetAdded();
                    }

                    db.CommandBuilder(string.Format(query.get_clientTaken, 0), tblClientTaken);

                    this.Tag = db.ExecuteScalar(query.get_clientTaken_ID); 
                    //this.Tag = db.ExecuteScalar(string.Format(query.scalarID_clientTaken, db.SqlString(cboClientCode.SelectedValue), cboZone.SelectedValue, cont_id));
                    //db.FillDataSet(string.Format(query.get_clientTaken, this.Tag), tblClientTaken);

                    foreach (DataGridViewRow r in dgTaken.Rows)
                    {
                        if (int.Parse(r.Cells["copy_id"].Value.ToString()) > 0)
                        {
                            db.ExecuteNonQuery(string.Format(query.add_copyTaken, this.Tag, r.Cells["taken_id"].Value, conf.CurUser));
                            db.ExecuteNonQuery(string.Format(query.add_copyAnalyse, db.ExecuteScalar(string.Format(query.get_takenId)), r.Cells["taken_id"].Value, conf.CurUser));
                        }
                    }

                    frmClient_Taken_Load(null, null);
                    btnCreate.Visible = true;
                }
            }
            else
            {
                // Check Identifiation dublicate field.
                string Taken_id = db.ExecuteScalar(string.Format(query.scalarID_clientTaken, db.SqlString(cboClientCode.SelectedValue), cboZone.SelectedValue, cont_id));
                if (Taken_id != "" && Taken_id != tblClientTaken.Rows[0]["client_taken_id"].ToString())
                {
                    MessageBox.Show(msg.cont_codeExistMsg, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    cboZone.Focus();
                    return;
                }

                if (MessageBox.Show(msg.saveMsg, msg.captionMsg, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    // Update contract into database.
                    row["client_taken_id"] = this.Tag;
                    tblClientTaken.Rows[0].ItemArray = row.ItemArray;

                    db.CommandBuilder(string.Format(query.get_clientTaken, this.Tag), tblClientTaken);
                }
            }
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            using (new WaitCursor())
            {
                Forms.frmTaken frm = new Forms.frmTaken();
                frm.client_taken_id = int.Parse(this.Tag.ToString());
                frm.cont_id = cont_id;
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    // Read taken record from database
                    db.FillDataSet(string.Format(query.get_taken_list, this.Tag, client_id_copy > 0 ? ",[client_taken_id] AS copy_id" : "", " AND [taken_id]=" + frm.Tag.ToString()), tblTaken, false, null, LoadOption.Upsert);
                    checkCopyRow();
                }
                
            }
        }

        private void dgTaken_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            if (client_id_copy > 0) 
            {
                MessageBox.Show(msg.cont_takenCopyCreateModify, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            
            Forms.frmTaken frm = new Forms.frmTaken();
            frm.client_taken_id = int.Parse(this.Tag.ToString());
            frm.cont_id = cont_id;
            frm.Tag = dgTaken.Rows[e.RowIndex].Cells["taken_id"].Value;
            if (int.Parse(dgTaken.CurrentRow.Cells["copy_id"].Value.ToString()) > 0) frm.taken_copy_id = int.Parse(frm.Tag.ToString());

            if (frm.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;

            // Delete record from list.
            tblTaken.Select(string.Format("taken_id={0}", dgTaken.CurrentRow.Cells["taken_id"].Value))[0].Delete();

            // Read taken record from database
            db.FillDataSet(string.Format(query.get_taken_list, this.Tag, client_id_copy > 0 ? ",[client_taken_id] AS copy_id" : "", " AND [taken_id]=" + frm.Tag.ToString()), tblTaken, false, null, LoadOption.OverwriteChanges);
            checkCopyRow();
            dgTaken.Rows[dgTaken.Rows.Count - 1].Selected = true;
        }

        private void dgTaken_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == dgTaken.Columns["colDelete"].Index)
            {
                if (int.Parse(dgTaken.CurrentRow.Cells["copy_id"].Value.ToString()) > 0)
                {
                    tblTaken.Select(string.Format("taken_id={0}", dgTaken.CurrentRow.Cells["taken_id"].Value))[0].Delete();
                    return;
                }
                Libraies.msg msg = new Libraies.msg();
                if (MessageBox.Show(msg.deleteMsg, msg.captionMsg, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    // Delete record from database.
                    db.ExecuteNonQuery(string.Format(query.del_analy_taken, dgTaken.CurrentRow.Cells["taken_id"].Value));
                    db.ExecuteNonQuery(string.Format(query.del_taken, dgTaken.CurrentRow.Cells["taken_id"].Value));

                    // Delete record from list.
                    tblTaken.Select(string.Format("taken_id={0}", dgTaken.CurrentRow.Cells["taken_id"].Value))[0].Delete();
                }
            }
        }

        private void checkCopyRow()
        {
            foreach (DataGridViewRow r in dgTaken.Rows)
                if (int.Parse(r.Cells["copy_id"].Value.ToString()) > 0) r.DefaultCellStyle.BackColor = Color.Crimson;
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            if (int.Parse(dgTaken.CurrentRow.Cells["copy_id"].Value.ToString()) > 0) return;
            Forms.frmTaken frm = new Forms.frmTaken();
            frm.client_taken_id = int.Parse(this.Tag.ToString());
            frm.Tag = dgTaken.Rows[dgTaken.CurrentRow.Index].Cells["taken_id"].Value;
            frm.taken_copy_id = int.Parse(frm.Tag.ToString());
            frm.cont_id = cont_id;

            if (frm.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;

            // Read taken record from database
            db.FillDataSet(string.Format(query.get_taken_list, this.Tag, client_id_copy > 0 ? ",[client_taken_id] AS copy_id" : "", " AND [taken_id]=" + frm.Tag.ToString()), tblTaken, false, null, LoadOption.OverwriteChanges);
            checkCopyRow();
        }

        private void tblTaken_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            btnCopy.Visible = tblTaken.Rows.Count > 0 ? true : false;
        }

        private void frmClient_Taken_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (client_id_copy == 0)
            {
                foreach (DataGridViewRow r in dgTaken.Rows)
                {
                    if (int.Parse(r.Cells["copy_id"].Value.ToString()) > 0)
                    {
                        if (MessageBox.Show(msg.cont_takenClientExitMsg, msg.captionMsg, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                        {
                            e.Cancel = true;
                            break;
                        }
                        else
                            break;
                    }
                }
            }
        }

    }
}
